package org.jeecg.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.JeecgBaseConfig;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.asAssessorInfo.entity.AsAssessorInfo;
import org.jeecg.modules.asAssessorInfo.service.IAsAssessorInfoService;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.model.SysLoginModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;

/**
 * @name: testController
 * @author: zhoushuo
 * @date: 2023-03-02 00:09
 **/
@Slf4j
@RestController
public class testController {

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private IAsAssessorInfoService asAssessorInfoService;

    @Autowired
    private JeecgBaseConfig jeecgBaseConfig;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private BaseCommonService baseCommonService;


    @ApiOperation("登录接口")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<JSONObject> login(@RequestBody SysLoginModel sysLoginModel){
        Result<JSONObject> result = new Result<JSONObject>();
        String username = sysLoginModel.getUsername();
        String password = sysLoginModel.getPassword();

        //1. 校验用户是否有效
        LambdaQueryWrapper<AsAssessorInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AsAssessorInfo::getUsername,username);
        AsAssessorInfo sysUser = asAssessorInfoService.getOne(queryWrapper);
        //result = sysUserService.checkUserIsEffective(sysUser);
        //if(!result.isSuccess()) {
        //    return result;
        //}

        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.md5BySalt(password, sysUser.getSalt());
        String syspassword = sysUser.getPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }
        //用户登录信息
        userInfo(sysUser, result);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser, loginUser);
        baseCommonService.addLog("评估员: " + username + ",登录成功！", CommonConstant.LOG_TYPE_1, null,loginUser);
        return result;
    }

    /**
     * 用户信息
     *
     * @param sysUser
     * @param result
     * @return
     */
    private Result<JSONObject> userInfo(AsAssessorInfo sysUser, Result<JSONObject> result) {
        String username = sysUser.getUsername();
        String syspassword = sysUser.getPassword();
        // 获取用户部门信息
        JSONObject obj = new JSONObject(new LinkedHashMap<>());

        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_APP_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_APP_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        obj.put("token", token);

        obj.put("userInfo", sysUser);

        //List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
        //obj.put("departs", departs);
        //if (departs == null || departs.size() == 0) {
        //    obj.put("multi_depart", 0);
        //} else if (departs.size() == 1) {
        //    sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
        //    obj.put("multi_depart", 1);
        //} else {
        //    //查询当前是否有登录部门
        //    // update-begin--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
        //    SysUser sysUserById = sysUserService.getById(sysUser.getId());
        //    if(oConvertUtils.isEmpty(sysUserById.getOrgCode())){
        //        sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
        //    }
        //    // update-end--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
        //    obj.put("multi_depart", 2);
        //}
        //obj.put("sysAllDictItems", sysDictService.queryAllDictItems());
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }



    @GetMapping("/hello")
    public Result<?> hello(HttpServletRequest req, SysDepart depart) {
        Page<SysDepart> page = new Page<>(1, 10);
        QueryWrapper<SysDepart> mockEntityQueryWrapper = QueryGenerator.initQueryWrapper(depart, req.getParameterMap());
        IPage<SysDepart> pageList = sysDepartService.page(page, mockEntityQueryWrapper);
        return Result.ok(pageList);
    }



}
